package smartterracedfieldsolution.smartteracedfieldsolution.service.service;

import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import smartterracedfieldsolution.smartteracedfieldsolution.common.result.Result;
import smartterracedfieldsolution.smartteracedfieldsolution.pojo.dto.RegisterRequest;
import smartterracedfieldsolution.smartteracedfieldsolution.pojo.entity.User;
import smartterracedfieldsolution.smartteracedfieldsolution.service.mapper.UserMapper;

import java.time.LocalDateTime;

@Service
public class UserService {
    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;

    @Autowired
    public UserService(UserMapper userMapper, PasswordEncoder passwordEncoder) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
    }

    /*
    用户登录
     */
    public User login(String username, String password) {
        User user = userMapper.selectByUserName(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        if(!passwordEncoder.matches(password, user.getPassword())){
            throw new RuntimeException("密码错误");
        }
        if(user.getStatus() == 0 ){
            throw new RuntimeException("用户已被禁用");
        }
        return user;
    }

    /*
    用户注册
     */
    public Result<Boolean> register(RegisterRequest request){
        if(userMapper.existsByUserName(request.getUserName())){
            return Result.fail(409, "用户名已存在");
        }
        if(userMapper.existsByPhone(request.getPhone())){
            return Result.fail(408,"该手机号已被注册");
        }
        User user = new User();
        user.setUserName(request.getUserName());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setPhone(request.getPhone());
        user.setFullName(request.getFullName());
        user.setStatus(1);
        try{
            userMapper.insert(user);
            return Result.success(true, "注册成功");
        }catch (DuplicateKeyException e){
            return Result.fail(409, "用户名或手机号已被注册");
        }catch (Exception e){
            System.out.println("注册失败："+e.getMessage());
            return Result.fail(500,"系统错误");
        }
    }
}
